package com.tg.app.activity.device.add;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.appbase.custom.config.ApiUrl;
import com.appbase.custom.constant.CommonConstants;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.core.device.manage.DeviceRename;
import com.tange.module.camera.hub.CameraHub;
import com.tg.app.R;
import com.tg.app.listener.OnAddDeviceListener;
import com.tg.app.util.LocalThumbnailUtils;
import com.tg.app.util.ObjectBoxUtil;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.data.bean.DeviceItem;
import com.tg.data.bean.DeviceItem_;
import com.tg.network.http.TimeZoneUtils;


public class SetDeviceNameFragment extends Fragment {
    public static final String TAG ="SetDeviceNameFragment" ;
    private static final String ARG_DEVICE_ID = "device_id";
    private static final String ARG_DEVICE_UUID = "device_uuid";
    private static final String ARG_DEVICE_ICCID = "device_iccid";
    private static final String ARG_DEVICE_AUTH = "device_auth";
    private long deviceID;
    private String deviceUUID;
    private EditText edtName;
    private ImageView ivClear;
    private OnAddDeviceListener listener;
    private static final int SET_NAME_SUCCESS = 1;
    private Button btnSetName;
    private TextView laterTextView;
    private boolean isApLocal = false;
    private String mIccId;
    private int mAuthStatus = 0;

    public void setListener(OnAddDeviceListener listener) {
        this.listener = listener;
    }

    public SetDeviceNameFragment() {
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == SET_NAME_SUCCESS) {
                int result = msg.arg1;
                if (result == 1) {
                    TGToast.showToast(R.string.setting_success);
                } else {
                    TGToast.showToast(R.string.setting_fail);
                }
                if (mAuthStatus == 1){
                    Intent intent = new Intent();
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.putExtra(ApiUrl.DEVICEID, deviceID);
                    intent.putExtra(ApiUrl.DEVICE_AUTH, mIccId);
                    intent.setClass(getContext(), TipDialogActivity.class);
                    startActivity(intent);
                }else{
                    if (listener != null) {
                        listener.onFinish(isApLocal);
                    }
                }
            }
            return false;
        }
    });

    public static SetDeviceNameFragment newInstance(long id, String uuid, int authStatus, String iccId) {
        SetDeviceNameFragment fragment = new SetDeviceNameFragment();
        Bundle args = new Bundle();
        args.putLong(ARG_DEVICE_ID, id);
        args.putString(ARG_DEVICE_UUID, uuid);
        args.putString(ARG_DEVICE_ICCID, iccId);
        args.putInt(ARG_DEVICE_AUTH, authStatus);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            deviceID = getArguments().getLong(ARG_DEVICE_ID);
            deviceUUID = getArguments().getString(ARG_DEVICE_UUID);
            mIccId = getArguments().getString(ARG_DEVICE_ICCID);
            mAuthStatus = getArguments().getInt(ARG_DEVICE_AUTH);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        edtName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(editable.toString())) {
                    ivClear.setVisibility(View.GONE);
                } else {
                    ivClear.setVisibility(View.VISIBLE);
                }
            }
        });
        ivClear.setOnClickListener(view -> edtName.setText(""));
        btnSetName.setOnClickListener(view -> setDeviceName());
        int num = 1;
        if (CameraHub.getInstance().isEnableLocalApConnect()) {
            //添加设备到本地
            num += PreferenceUtil.getInt(getContext(), CommonConstants.PRE_DEVICE_LOCAL_NUM, 0);
        } else {
            num += PreferenceUtil.getInt(getContext(), CommonConstants.PRE_DEVICE_NUM, 0);
            setTimezone();
        }
        edtName.setText(getString(R.string.camera) + num);
    }

    private void setTimezone() {
        TimeZoneUtils.setTimezone(String.valueOf(deviceID));
    }

    private void setDeviceName() {
        String name = edtName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            name = "Camera";
        }
        if (CameraHub.getInstance().isEnableLocalApConnect()) {
            updateLocalDeviceName(name);
            return;
        }

        DeviceRename.INSTANCE.require(deviceUUID, name, ret -> {
            if (ret.getSuccess()) {
                TGLog.i(TAG, "[request] success");
                handler.sendMessage(handler.obtainMessage(SET_NAME_SUCCESS, 1, 0));
            } else {
                TGLog.i(TAG, "[request] fail");
                handler.sendMessage(handler.obtainMessage(SET_NAME_SUCCESS, 0, ret.getCode()));
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_set_device_name, container, false);
        edtName = view.findViewById(R.id.edt_set_device_name);
        ivClear = view.findViewById(R.id.iv_set_name_clear);
        btnSetName = view.findViewById(R.id.btn_set_device_name_submit);
        laterTextView = view.findViewById(R.id.how_to_connect_device);
        laterTextView.setOnClickListener(v -> {});
        return view;
    }

    private void updateLocalDeviceName(String name) {
        DeviceItem deviceItem = ObjectBoxUtil.getDeviceItem().query().equal(DeviceItem_.uuid, deviceUUID).build().findFirst();
        deviceItem.name = name;
        ObjectBoxUtil.getDeviceItem().put(deviceItem);
        isApLocal = true;
        int i = (int) (deviceItem.id - 1);
        LocalThumbnailUtils.getInstance().deleteBitmap(deviceUUID);
        handler.sendMessage(handler.obtainMessage(SET_NAME_SUCCESS, 1, 0));
    }

    @Override
    public void onDetach() {
        super.onDetach();
        handler.removeCallbacksAndMessages(this);
    }
}
